import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/tap_text.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:flutter/cupertino.dart";

class BottomSheetSelect extends StatefulWidget {
  final List items;
  final bool Function(dynamic)? compare;
  final String Function(dynamic)? itemAsString;

  const BottomSheetSelect({
    super.key,
    required this.items,
    this.compare,
    this.itemAsString,
  });

  @override
  State<BottomSheetSelect> createState() => _BottomSheetSelectState();
}

class _BottomSheetSelectState extends State<BottomSheetSelect> {
  int _selected = 0;

  @override
  void initState() {
    super.initState();
    if (widget.compare != null) {
      int found = widget.items.indexWhere(widget.compare!);
      if (found != -1) _selected = found;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
          child: DefaultTextStyle(
            style: DefaultTextStyle.of(context).style.copyWith(fontSize: 16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TapText(onTap: Stacker.pop, text: "取消"),
                TapText(
                  onTap: () => Stacker.pop(widget.items[_selected]),
                  text: "确定",
                ),
              ],
            ),
          ),
        ),
        const SolidDivider(padding: EdgeInsets.only(bottom: 8)),
        SizedBox(
          height: 240,
          child: CupertinoPicker(
            itemExtent: 48,
            scrollController:
                FixedExtentScrollController(initialItem: _selected),
            onSelectedItemChanged: (int value) => _selected = value,
            children: widget.items.map((ele) {
              String text = widget.itemAsString == null
                  ? ele.toString()
                  : widget.itemAsString!(ele);
              return Center(
                child: Text(text, style: const TextStyle(fontSize: 16)),
              );
            }).toList(),
          ),
        ),
      ],
    );
  }
}
